#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>

int get_interface_mac_ipaddr(char *interf,char *mac,char *ipaddr)
{
    struct ifreq ifr;
    struct ifconf ifc;
    char buf[2048];
    int success = 0;
 
    int socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketfd == -1) {
        printf("socket error\n");
        return -1;
    }

    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = buf;
    /* get iface list 得到所有网络接口信息列表	*/
    if (ioctl(socketfd, SIOCGIFCONF, &ifc) == -1) { 
        printf("ioctl SIOCGIFCONF is error\n");
        return -1;
    }
    // printf("ifc.ifc_len = %d\n",ifc.ifc_len);

    struct ifreq* it = ifc.ifc_req;
    const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq));
    char szMac[64];
    char ipAddr[16];
    int count = 0;
    for (; it != end; ++it) {
        strcpy(ifr.ifr_name, it->ifr_name);
        if (ioctl(socketfd, SIOCGIFFLAGS, &ifr) == 0) {
            if (! (ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
                if (ioctl(socketfd, SIOCGIFHWADDR, &ifr) == 0) { //获取mac地址
                    unsigned char * ptr ;
                    ptr = (unsigned char  *)&ifr.ifr_ifru.ifru_hwaddr.sa_data[0];
                    snprintf(szMac,64,"%02X%02X%02X%02X%02X%02X",*ptr,*(ptr+1),*(ptr+2),*(ptr+3),*(ptr+4),*(ptr+5));
                }
                if (ioctl(socketfd, SIOCGIFADDR, &ifr) == 0){ //获取ip地址
                    strcpy(ipAddr,inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
                }
                // printf("%d\n",count++);
                // printf("    --Interface name: %s \n",ifr.ifr_name);
                // printf("    --Mac address:    %s\n",szMac);
                // printf("    --inet:           %s\n",ipAddr);
                strcpy(interf,ifr.ifr_name);
                strcpy(mac,szMac);
                strcpy(ipaddr,ipAddr);
            }
        }else{
            printf("get mac info error\n");
            return -1;
        }
    }
    return 0;

}

#if 0
int main()
{
    char interface[10];
    char szMac[64];
    char ipAddr[16];
    get_interface_mac_ipaddr(interface,szMac,ipAddr);
    printf("%s\n",interface);
    printf("%s\n",szMac);
    printf("%s\n",ipAddr);

    return 0;
}
#endif
